package com.cy.helmet;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.Toast;


import java.io.IOException;
import java.util.List;

public class Camera1PreviewActivity extends Activity implements
        SurfaceHolder.Callback,
        Camera.AutoFocusCallback {

    private static final String TAG = "Camera1Preview";
    private static final int CAMERA_REQUEST_CODE = 100;

    private SurfaceView surfaceView;
    private SurfaceHolder surfaceHolder;
    private Camera camera;
    private int cameraId = Camera.CameraInfo.CAMERA_FACING_BACK;

    private Button btnSwitchCamera;
    private Button btnFlash;
    private Button btnFocus;
    private Button btnCapture;
    private LinearLayout controlLayout;

    private boolean isFlashOn = false;
    private boolean isFrontCamera = false;
    private int displayOrientation = 0;

    // 预览尺寸
    private Camera.Size previewSize;
    private int previewWidth = 0;
    private int previewHeight = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 保持屏幕常亮
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        // 全屏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_camera_preview);

        initViews();

        // 检查权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CAMERA},
                    CAMERA_REQUEST_CODE);
        } else {
            initCamera();
        }
    }

    private void initViews() {
        surfaceView = findViewById(R.id.surfaceView);
        btnSwitchCamera = findViewById(R.id.btnSwitchCamera);
        btnFlash = findViewById(R.id.btnFlash);
        btnFocus = findViewById(R.id.btnFocus);
        btnCapture = findViewById(R.id.btnCapture);
        controlLayout = findViewById(R.id.controlLayout);

        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(this);

        // 设置按钮点击监听
        btnSwitchCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switchCamera();
            }
        });
        btnFlash.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toggleFlash();
            }
        });
        btnFocus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                triggerAutoFocus();
            }
        });
        btnCapture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                takePicture();
            }
        });

        // 设置SurfaceView触摸监听（手动对焦）
        surfaceView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (camera != null && event.getAction() == android.view.MotionEvent.ACTION_UP) {
                    handleTouchFocus(event.getX(), event.getY());
                }
                return true;
            }
        });

        // 控制栏显示/隐藏
        surfaceView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toggleControls();
            }
        });
    }

    private void initCamera() {
        if (camera != null) {
            releaseCamera();
        }

        try {
            camera = Camera.open(cameraId);
            setupCameraParameters();

            // 设置预览方向
            setCameraDisplayOrientation();

        } catch (Exception e) {
            Log.e(TAG, "Failed to open camera: " + e.getMessage());
            Toast.makeText(this, "无法打开相机", Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    private void setupCameraParameters() {
        if (camera == null) return;

        Camera.Parameters parameters = camera.getParameters();

        // 获取支持的预览尺寸并选择最佳尺寸
        List<Camera.Size> supportedPreviewSizes = parameters.getSupportedPreviewSizes();
        previewSize = getOptimalPreviewSize(supportedPreviewSizes,
                1280,
                720);

        if (previewSize != null) {
            parameters.setPreviewSize(previewSize.width, previewSize.height);
            previewWidth = previewSize.width;
            previewHeight = previewSize.height;
            Log.d(TAG, "Preview size: " + previewWidth + "x" + previewHeight);
        }

        // 设置图片格式
        parameters.setPreviewFormat(ImageFormat.NV21);

        // 设置对焦模式
        List<String> focusModes = parameters.getSupportedFocusModes();
        if (focusModes != null) {
            if (focusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {
                parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
            } else if (focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
                parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
            }
        }

        // 设置闪光灯模式
        List<String> flashModes = parameters.getSupportedFlashModes();
        if (flashModes != null && flashModes.contains(Camera.Parameters.FLASH_MODE_OFF)) {
            parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
        }

        // 设置场景模式
        List<String> sceneModes = parameters.getSupportedSceneModes();
        if (sceneModes != null && sceneModes.contains(Camera.Parameters.SCENE_MODE_AUTO)) {
            parameters.setSceneMode(Camera.Parameters.SCENE_MODE_AUTO);
        }

        // 设置白平衡
        List<String> whiteBalance = parameters.getSupportedWhiteBalance();
        if (whiteBalance != null && whiteBalance.contains(Camera.Parameters.WHITE_BALANCE_AUTO)) {
            parameters.setWhiteBalance(Camera.Parameters.WHITE_BALANCE_AUTO);
        }

        try {
            camera.setParameters(parameters);
        } catch (RuntimeException e) {
            Log.e(TAG, "Camera parameters set failed: " + e.getMessage());
        }
    }

    private Camera.Size getOptimalPreviewSize(List<Camera.Size> sizes, int w, int h) {
        final double ASPECT_TOLERANCE = 0.1;
        double targetRatio = (double) w / h;

        if (sizes == null) return null;

        Camera.Size optimalSize = null;
        double minDiff = Double.MAX_VALUE;

        // 尝试找到与屏幕比例最匹配的尺寸
        for (Camera.Size size : sizes) {
            double ratio = (double) size.width / size.height;
            if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
            if (Math.abs(size.height - h) < minDiff) {
                optimalSize = size;
                minDiff = Math.abs(size.height - h);
            }
        }

        // 如果没有找到比例匹配的，选择与屏幕高度最接近的
        if (optimalSize == null) {
            minDiff = Double.MAX_VALUE;
            for (Camera.Size size : sizes) {
                if (Math.abs(size.height - h) < minDiff) {
                    optimalSize = size;
                    minDiff = Math.abs(size.height - h);
                }
            }
        }

        return optimalSize;
    }

    private void setCameraDisplayOrientation() {
        if (camera == null) return;

        Camera.CameraInfo info = new Camera.CameraInfo();
        Camera.getCameraInfo(cameraId, info);

        int rotation = getWindowManager().getDefaultDisplay().getRotation();
        int degrees = 0;
        switch (rotation) {
            case Surface.ROTATION_0:
                degrees = 0;
                break;
            case Surface.ROTATION_90:
                degrees = 90;
                break;
            case Surface.ROTATION_180:
                degrees = 180;
                break;
            case Surface.ROTATION_270:
                degrees = 270;
                break;
        }

        int result;
        if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            result = (info.orientation + degrees) % 360;
            result = (360 - result) % 360;  // 镜像
        } else {
            result = (info.orientation - degrees + 360) % 360;
        }

        camera.setDisplayOrientation(result);
        displayOrientation = result;
        Log.d(TAG, "Display orientation: " + result);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        Log.d(TAG, "Surface created");
        startPreview();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        Log.d(TAG, "Surface changed: " + width + "x" + height);
        if (surfaceHolder.getSurface() == null) return;

        stopPreview();
        startPreview();
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        Log.d(TAG, "Surface destroyed");
        stopPreview();
    }

    private void startPreview() {
        if (camera == null) return;

        try {
            camera.setPreviewDisplay(surfaceHolder);
            camera.startPreview();

            // 设置预览回调（可选）
            camera.setPreviewCallback(new Camera.PreviewCallback() {
                @Override
                public void onPreviewFrame(byte[] data, Camera camera) {
                    // 可以在这里处理预览帧数据
                    // Log.d(TAG, "Preview frame received");
                }
            });

            Log.d(TAG, "Preview started");
        } catch (IOException e) {
            Log.e(TAG, "Error starting preview: " + e.getMessage());
        }
    }

    private void stopPreview() {
        if (camera != null) {
            camera.stopPreview();
            camera.setPreviewCallback(null);
            Log.d(TAG, "Preview stopped");
        }
    }

    private void releaseCamera() {
        if (camera != null) {
            stopPreview();
            camera.release();
            camera = null;
            Log.d(TAG, "Camera released");
        }
    }

    private void switchCamera() {
        if (Camera.getNumberOfCameras() <= 1) {
            Toast.makeText(this, "没有可切换的摄像头", Toast.LENGTH_SHORT).show();
            return;
        }

        // 切换摄像头ID
        cameraId = (cameraId == Camera.CameraInfo.CAMERA_FACING_BACK)
                ? Camera.CameraInfo.CAMERA_FACING_FRONT
                : Camera.CameraInfo.CAMERA_FACING_BACK;

        isFrontCamera = (cameraId == Camera.CameraInfo.CAMERA_FACING_FRONT);

        releaseCamera();
        initCamera();

        // 如果是前置摄像头，关闭闪光灯
        if (isFrontCamera && isFlashOn) {
            toggleFlash();
        }

        // 更新闪光灯按钮状态
        updateFlashButtonState();

        Toast.makeText(this, isFrontCamera ? "切换到前置摄像头" : "切换到后置摄像头",
                Toast.LENGTH_SHORT).show();
    }

    private void toggleFlash() {
        if (camera == null || isFrontCamera) return;

        Camera.Parameters parameters = camera.getParameters();
        List<String> flashModes = parameters.getSupportedFlashModes();

        if (flashModes == null || flashModes.isEmpty()) {
            Toast.makeText(this, "该摄像头不支持闪光灯", Toast.LENGTH_SHORT).show();
            return;
        }

        String flashMode;
        if (isFlashOn) {
            // 关闭闪光灯
            if (flashModes.contains(Camera.Parameters.FLASH_MODE_OFF)) {
                flashMode = Camera.Parameters.FLASH_MODE_OFF;
                btnFlash.setText("闪光灯关");
            } else {
                return;
            }
        } else {
            // 打开闪光灯
            if (flashModes.contains(Camera.Parameters.FLASH_MODE_TORCH)) {
                flashMode = Camera.Parameters.FLASH_MODE_TORCH;
                btnFlash.setText("闪光灯开");
            } else if (flashModes.contains(Camera.Parameters.FLASH_MODE_ON)) {
                flashMode = Camera.Parameters.FLASH_MODE_ON;
                btnFlash.setText("闪光灯开");
            } else {
                return;
            }
        }

        parameters.setFlashMode(flashMode);
        try {
            camera.setParameters(parameters);
            isFlashOn = !isFlashOn;
        } catch (RuntimeException e) {
            Log.e(TAG, "Flash mode set failed: " + e.getMessage());
        }
    }

    private void updateFlashButtonState() {
        if (isFrontCamera) {
            btnFlash.setEnabled(false);
            btnFlash.setText("闪光灯");
        } else {
            btnFlash.setEnabled(true);
            btnFlash.setText(isFlashOn ? "闪光灯开" : "闪光灯关");
        }
    }

    private void triggerAutoFocus() {
        if (camera == null) return;

        try {
            Camera.Parameters parameters = camera.getParameters();
            List<String> focusModes = parameters.getSupportedFocusModes();

            if (focusModes != null && focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
                parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
                camera.setParameters(parameters);
                camera.autoFocus(this);
            } else {
                Toast.makeText(this, "该摄像头不支持自动对焦", Toast.LENGTH_SHORT).show();
            }
        } catch (RuntimeException e) {
            Log.e(TAG, "Auto focus failed: " + e.getMessage());
        }
    }

    @Override
    public void onAutoFocus(boolean success, Camera camera) {
        if (success) {
            Log.d(TAG, "Auto focus success");
            Toast.makeText(this, "对焦成功", Toast.LENGTH_SHORT).show();
        } else {
            Log.d(TAG, "Auto focus failed");
            Toast.makeText(this, "对焦失败", Toast.LENGTH_SHORT).show();
        }
    }

    private void handleTouchFocus(float x, float y) {
        if (camera == null) return;

        try {
            Camera.Parameters parameters = camera.getParameters();

            // 检查是否支持触摸对焦
            if (!parameters.getSupportedFocusModes().contains(
                    Camera.Parameters.FOCUS_MODE_AUTO)) {
                return;
            }

            // 设置对焦区域
            Rect focusRect = calculateTapArea(x, y, 1f);
            Rect meteringRect = calculateTapArea(x, y, 1.5f);

            parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);

            if (parameters.getMaxNumFocusAreas() > 0) {
                List<Camera.Area> focusAreas = new java.util.ArrayList<>();
                focusAreas.add(new Camera.Area(focusRect, 1000));
                parameters.setFocusAreas(focusAreas);
            }

            if (parameters.getMaxNumMeteringAreas() > 0) {
                List<Camera.Area> meteringAreas = new java.util.ArrayList<>();
                meteringAreas.add(new Camera.Area(meteringRect, 1000));
                parameters.setMeteringAreas(meteringAreas);
            }

            camera.setParameters(parameters);
            camera.autoFocus(this);

        } catch (RuntimeException e) {
            Log.e(TAG, "Touch focus failed: " + e.getMessage());
        }
    }

    private Rect calculateTapArea(float x, float y, float coefficient) {
        int areaSize = Float.valueOf(100 * coefficient).intValue();

        int left = clamp((int) x - areaSize / 2, 0, previewWidth - areaSize);
        int top = clamp((int) y - areaSize / 2, 0, previewHeight - areaSize);

        RectF rectF = new RectF(left, top, left + areaSize, top + areaSize);
        Matrix matrix = new Matrix();
        matrix.setRotate(-displayOrientation);
        matrix.mapRect(rectF);

        return new Rect(Math.round(rectF.left), Math.round(rectF.top),
                Math.round(rectF.right), Math.round(rectF.bottom));
    }

    private int clamp(int x, int min, int max) {
        if (x > max) return max;
        if (x < min) return min;
        return x;
    }

    private void takePicture() {
        if (camera == null) return;

        try {
            camera.takePicture(null, null, new Camera.PictureCallback() {
                @Override
                public void onPictureTaken(byte[] data, Camera camera) {
                    // 处理拍照数据
                    Log.d(TAG, "Picture taken, size: " + (data != null ? data.length : 0));
                    Toast.makeText(Camera1PreviewActivity.this, "拍照完成", Toast.LENGTH_SHORT).show();

                    // 重新开始预览
                    camera.startPreview();
                }
            });
        } catch (RuntimeException e) {
            Log.e(TAG, "Take picture failed: " + e.getMessage());
            Toast.makeText(this, "拍照失败", Toast.LENGTH_SHORT).show();
        }
    }

    private void toggleControls() {
        if (controlLayout.getVisibility() == View.VISIBLE) {
            controlLayout.setVisibility(View.INVISIBLE);
        } else {
            controlLayout.setVisibility(View.VISIBLE);
            // 3秒后自动隐藏
            surfaceView.postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            controlLayout.setVisibility(View.INVISIBLE);
                                        }
                                    }
                    , 3000);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == CAMERA_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                initCamera();
            } else {
                Toast.makeText(this, "需要相机权限才能使用此功能", Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (camera == null && ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                == PackageManager.PERMISSION_GRANTED) {
            initCamera();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        releaseCamera();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        releaseCamera();
    }
}
